<template>
  <div>
    <pro-table
      ref="tableRef"
      :data="tableData"
      :total="total"
      :columns="columns"
      :tool-button="false"
      @search="commEvent.onSearch"
      :page-change="commEvent.onPageChange"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- 顶部配置项 -->
      <template #tableHeader>
        <el-row justify="end">
          <el-button type="primary" icon="Plus" @click="commEvent.onSave()">新增</el-button>
        </el-row>
      </template>
      <!-- 操作 -->
      <template #operation="{ row }">
        <el-button type="primary" link @click="commEvent.onSave(row)">编辑</el-button>
        <el-button type="danger" link @click="commEvent.onDelete(row)">删除</el-button>
        <el-button type="default" link @click="commEvent.onPoint(row)">点位</el-button>
        <el-button type="info" link @click="commEvent.onDetail(row)">详情</el-button>
      </template>
    </pro-table>
    <!-- 新增/编辑 -->
    <save-meter
      v-model="saveVisible"
      :rows="currRow"
      :factorys="factoryEnum"
      :lines="lineEnum"
      :devicet-types="deviceTypeEnum"
      :comm-modes="commsModeEnum"
      :gate-ways="gateWayEnum"
      @refresh="commEvent.onSearch"
    />
    <!-- 详情 -->
    <Detail v-model="detailVisible" title="设备详情" :columns="detailColumns" :data="detailData" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import ProTable from "@/components/ProTable/index.vue"
import SaveMeter from "./components/SaveMeter.vue"
import Detail from "@/components/MyDetail/index.vue"
import { ColumnProps, ProTableInstance, EnumProps } from "@/components/ProTable/interface"
import { ElMessage, ElMessageBox } from "element-plus"
import { energyTypeEnum } from "@/utils/enum"
import { useRouter } from "vue-router"
import { dataDictionaryMeter, dataDictionaryMode, organByLevel } from "@/api/modules/system"
import { meterPage, gatewayList, deleteMeter, meterDetail } from "@/api/modules/archive"
import { SystemSpace } from "@/api/interface/archive"
import { DetailColumns } from "@/components/MyDetail"
// 参数
const router = useRouter()
const tableRef = ref<ProTableInstance>() // 表格实例
const tableData = ref<SystemSpace.MeterPage[]>([]) // 表格数据
const total = ref<number>(0) // 数据总数
const saveVisible = ref<boolean>(false) // 新增/编辑弹窗
const detailData = ref<SystemSpace.MeterDetail>() // 详情数据
const detailVisible = ref<boolean>(false) // 新增/编辑弹窗
const currRow = ref<SystemSpace.MeterPage>() // 当前选中数据
const factoryEnum = ref<EnumProps[]>([]) // 厂区
const lineEnum = ref<EnumProps[]>([]) // 产线
const deviceTypeEnum = ref<EnumProps[]>([]) // 设备类型
const commsModeEnum = ref<EnumProps[]>([]) // 通讯模式
const gateWayEnum = ref<EnumProps[]>([]) // 网关信息
// 页码参数
const pageParams = ref({
  pageIndex: 1,
  pageSize: 10
})
// 表格列配置
const columns: ColumnProps<SystemSpace.MeterPage>[] = [
  { prop: "factoryId", label: "所属厂区", width: 160, enum: factoryEnum, search: { el: "select" } },
  { prop: "lineId", label: "所属产线", width: 160, enum: lineEnum, search: { el: "select" } },
  { prop: "gatewayCode", label: "网关编码", width: 160, search: { el: "input" } },
  { prop: "code", label: "设备编码", width: 120, search: { el: "input" } },
  { prop: "name", label: "设备名称", width: 160, search: { el: "input" } },
  { prop: "meterType", label: "设备类型", width: 160, enum: deviceTypeEnum, search: { el: "select" } },
  { prop: "energyType", label: "能源类型", width: 160, enum: energyTypeEnum, search: { el: "select" } },
  { prop: "commsMode", label: "通讯模式", width: 160, enum: commsModeEnum },
  { prop: "createBy", label: "创建人", minWidth: 160 },
  { prop: "createTime", label: "创建时间", minWidth: 180 },
  { prop: "operation", label: "操作", width: 240, fixed: "right" }
]
// 详情配置
const initColumns: DetailColumns[] = [
  {
    key: "factoryId",
    label: "所属厂区",
    format: (val: number) => factoryEnum.value.find(item => item.value === val)?.label || ""
  },
  { key: "lineId", label: "所属产线", format: (val: number) => lineEnum.value.find(item => item.value === val)?.label || "" },
  { key: "gatewayCode", label: "网关编码" },
  { key: "code", label: "设备编码" },
  { key: "name", label: "设备名称", span: 16 },
  {
    key: "meterType",
    label: "设备类型",
    format: (val: number) => deviceTypeEnum.value.find(item => item.value === val)?.label || ""
  },
  { key: "energyType", label: "能源类型", format: (val: number) => energyTypeEnum.find(item => item.value === val)?.label || "" },
  {
    key: "commsMode",
    label: "通讯模式",
    format: (val: number) => commsModeEnum.value.find(item => item.value === val)?.label || ""
  },
  { key: "modelNumber", label: "规格型号" },
  { key: "location", label: "安装位置", span: 16 },
  { key: "manufacturer", label: "生产厂家" },
  { key: "productionDate", label: "生产日期" },
  { key: "putrunDate", label: "投运日期" },
  { key: "personCharge", label: "负责人" },
  { key: "createBy", label: "创建人" },
  { key: "createTime", label: "创建时间" }
]
const detailColumns = computed<DetailColumns[]>(() => {
  let otherColumns: DetailColumns[] = []
  if (currRow.value?.energyType === "electric") {
    otherColumns = [
      { key: "rangeCurrentStop", label: "停机电流阈值" },
      { key: "rangeCurrentWait", label: "待机电流阈值" },
      { key: "rangeCurrentUpper", label: "电流上限阈值" }
    ]
  }
  return [...initColumns, ...otherColumns]
})
// 事件集合
const commEvent = {
  // 获取所属厂区
  getFactory: async () => {
    const { data } = await organByLevel(1)
    factoryEnum.value = data.map(item => ({
      label: item.organName,
      value: item.id
    }))
  },
  // 获取所属产线
  getLine: async () => {
    const { data } = await organByLevel(2)
    lineEnum.value = data.map(item => ({
      label: item.organName,
      value: item.id
    }))
  },
  // 获取设备类型
  getDeviceType: async () => {
    const { data } = await dataDictionaryMeter()
    Object.keys(data).forEach(item => {
      const _obj = { label: item, value: data[item] }
      deviceTypeEnum.value = [...deviceTypeEnum.value, _obj]
    })
  },
  // 获取通讯模式
  getCommsMode: async () => {
    const { data } = await dataDictionaryMode()
    Object.keys(data).forEach(item => {
      const _obj = { label: item, value: data[item] }
      commsModeEnum.value = [...commsModeEnum.value, _obj]
    })
  },
  // 获取网关
  getGateway: async () => {
    const { data } = await gatewayList()
    gateWayEnum.value = data.map(item => ({
      label: item.name,
      value: item.code
    }))
  },
  // 获取表格数据
  getTableData: async (params: SystemSpace.MeterPageQuery) => {
    const { data } = await meterPage(params)
    tableData.value = data.result
    total.value = data.totalCount
  },
  // 查询
  onSearch: () => {
    tableRef.value?.search()
    pageParams.value.pageIndex = 1
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  },
  // 分页
  onPageChange: (page: number, size: number) => {
    pageParams.value.pageIndex = page
    pageParams.value.pageSize = size
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  },
  //  新增/编辑
  onSave: (row?: SystemSpace.MeterPage) => {
    currRow.value = row
    saveVisible.value = true
  },
  // 删除
  onDelete: async (row: SystemSpace.MeterPage) => {
    ElMessageBox.confirm("确定删除此设备?", "删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        const { code } = await deleteMeter({ id: row.id })
        if (code !== "200") return
        ElMessage.success("删除成功")
        commEvent.onSearch()
      })
      .catch(() => {})
  },
  // 计量点位
  onPoint: (row: SystemSpace.MeterPage) => {
    router.push({ path: "/system/archive/meterage/point", query: { meterId: row.id } })
  },
  // 详情
  onDetail: async (row: SystemSpace.MeterPage) => {
    currRow.value = row
    const { data } = await meterDetail(row.id)
    detailData.value = data
    detailVisible.value = true
  }
}
onMounted(() => {
  commEvent.getTableData(pageParams.value)
  commEvent.getFactory()
  commEvent.getLine()
  commEvent.getDeviceType()
  commEvent.getCommsMode()
  commEvent.getGateway()
})
</script>

<style lang="scss" scoped></style>
